var _columns =[
	{checkbox: true},
	{field: 'id', title: '序号', align: 'center',	 valign: 'middle'},
	{title: '序号', field: 'showId', align: 'center',	 valign: 'middle',
		formatter:function(value,row,index){
			return index+1;
	}},
    {field: 'sensorName', title: '水表名称', align: 'center', valign: 'middle'},
    {field: 'sensorRowId', title: '水表编号', align: 'center', valign: 'middle',visible:true},
    {field: 'location', title: '所在位置', align: 'center', valign: 'middle'},
    {field: 'measuringRange', title: '计量范围(m³/h)', align: 'center', valign: 'middle'},
    {field: 'sensorModel', title: '水表型号', align: 'center', valign: 'middle'},
    {field: 'sensorAccuracy', title: '水表精度', align: 'center', valign: 'middle'},
    {field: 'remarks', title: '备注', align: 'center', valign: 'middle'},
    {field: 'userName', title: '操作人员', align: 'center', valign: 'middle'}
    
	]

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/eva_watersensor_info/query',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: false,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            //导出
            showExport: true,                     //是否显示导出按钮
            exportTypes:['csv', 'doc', 'excel'], //['csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],           //导出文件类型
            exportDataType: "all",             //basic当前页', 'all所有, 'selected'.
            exportOptions: {
                fileName: '全厂计量水表配备情况表',  //文件名称设置
                excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            company_id: label_entity_water_bala_companyID,
        };
        return temp;
    };
    return oTableInit;
};

var bigdata=null;
var ButtonInit = function () {
    var oInit = new Object();
    var entity_sensor_company_id;
    //已知水平衡测试一级页面的公司名称和公司id，查询设备管理中相同公司的id，此id属于technological_process表格中根据公司名称和模块名称为“设备管理”查询的结果
    $.ajax({
        type: 'get',
        url:"/eva_watersensor_info/query_entity_sensor_cid",
        data:{
            'testId':label_entity_water_bala_companyID
        },
        dataType:'json',
        async:false,
        contentType: "application/json; charset=utf-8",
        success:function(data){
            entity_sensor_company_id=data.rows;
        }
    });
    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_add").click(function () {
            $('#new_data').modal();
            $("#newSelect_id").empty();
            $("#newSelect2_id").empty();
//            $.ajax({
//    			type:'get',
//    			url:"/chart/selectSensor",
//    			data: {
//                    'companyId': entity_sensor_company_id
//                },
//    			dataType: 'json',
//    		    async: false,
//    		    contentType: "application/json; charset=utf-8",
//    			success:function(data){
//    				bigdata=data;
//    				change(data.results[0].名称,data.results[0].设备编号,0);
//    				sortdata(data.results);
////    				for(var i=0;i<data.results.length;i++){
////    					$("#newSelect_id").append("<option value='"+data.results[i].名称+"'>"+data.results[i].名称+"</option>");
////    				}
//    				change(data.results[0].名称,data.results[0].设备编号,0);
//    			},
//    		    error: function(){
//    		    	 bootoast({
//    	                    message: '错误',
//    	                    position: 'top',
//    	                    type: 'danger',
//    	                    timeout: 1.5,
//    	                });
//    		    }
//    		});
    		$.ajax({
                type: 'get',
                url: '/chart/querySensorNameByBusinessId',
                data: {
                    'businessId': entity_sensor_company_id
                },
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (res) {
                    let data = res.data
                    $('#newSelect_id').empty();
                    for (var i = 0; i < data.length; i++) {
                        $("#newSelect_id").append(
                            "<option value='" + data[i] + "'>" + data[i] +
                            "</option>");
                    }
                },
            });

            $("#newSelect_id").change(function () {
                $.ajax({
                    type: 'get',
                    url: '/chart/querySensorNoByName',
                    data: {
                        'businessId': entity_sensor_company_id,
                        'name':$('#newSelect_id').val()
                    },
                    dataType: 'json',
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        let data = res.data
                        $('#newSelect2_id').empty();
                        for (var i = 0; i < data.length; i++) {
                            $("#newSelect2_id").append(
                                "<option value='" + data[i] + "'>" + data[i] +
                                "</option>");
                        }
                        getOtherSensorInfo(entity_sensor_company_id)
                   },
                });
            })

            $("#newSelect2_id").change(function (){
                getOtherSensorInfo(entity_sensor_company_id);
            })



        });

        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            $('#edit_data').modal();
            $("#editSelect_id").empty();
//            $.ajax({
//    			type:'get',
//    			url:"/chart/selectSensor",
//    			dataType: 'json',
//    		    async: false,
//    		    contentType: "application/json; charset=utf-8",
//    			success:function(data){
//    				bigdata=data;
//    				for(var i=0;i<data.results.length;i++){
//    					$("#editSelect_id").append("<option value='"+data.results[i].名称+"'>"+data.results[i].名称+"</option>");
//    				}
//    			},
//    		    error: function(){
//    		    	 bootoast({
//    	                    message: '错误',
//    	                    position: 'top',
//    	                    type: 'danger',
//    	                    timeout: 1.5,
//    	                });
//    		    }
//    		});
            $.ajax({
                type: 'get',
                url: '/chart/querySensorNameByBusinessId',
                data: {
                    'businessId': entity_sensor_company_id
                },
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (res) {
                    let data = res.data
                    $('#editSelect_id').empty();
                    for (var i = 0; i < data.length; i++) {
                        $("#editSelect_id").append(
                            "<option value='" + data[i] + "'>" + data[i] +
                            "</option>");
                    }
                },
            });

            $("#editSelect_id").change(function () {
                $.ajax({
                    type: 'get',
                    url: '/chart/querySensorNoByName',
                    data: {
                        'businessId': entity_sensor_company_id,
                        'name':$('#editSelect_id').val()
                    },
                    dataType: 'json',
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        let data = res.data
                        $('#editSelect2_id').empty();
                        for (var i = 0; i < data.length; i++) {
                            $("#editSelect2_id").append(
                                "<option value='" + data[i] + "'>" + data[i] +
                                "</option>");
                        }
                        getOtherSensorInfoEdit(entity_sensor_company_id)
                   },
                });
            })

            $("#editSelect2_id").change(function (){
                getOtherSensorInfoEdit(entity_sensor_company_id);
            })
            document.getElementById("editSelect_id").value = arrselections[0]['sensorName'];
            document.getElementById("editSelect2_id").value = arrselections[0]['sensorRowId'];
            document.getElementById("editLocation").value = arrselections[0]['location'];
            document.getElementById('editRange').value = arrselections[0]['measuringRange'];
            document.getElementById('editType').value = arrselections[0]['sensorModel'];
            document.getElementById('editAccuracy').value = arrselections[0]['sensorAccuracy'];
            document.getElementById('editNote').value = arrselections[0]['remarks'];
           
        });
        
        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            values=[];
            for(var i=0;i<arrselections.length;i++)
                values.push(arrselections[i].id);
            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/eva_watersensor_info/delete",
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                } else {
                                    bootoast({
                                        message: '删除失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })

        });


        //新增框内的提交	
        $('#new_data_submit').on('click', function () {
            var sensorName = $('#newSelect_id').val()
            var location = $('#newLocation').val()
            var measuringRange = $('#newRange').val()
            var sensorModel = $('#newType').val()
            var sensorAccuracy = $('#newAccuracy').val()
            var remarks = $('#newNote').val()
            var sensorRowId=$('#newSelect2_id').val()
            //var companyId=label_entity_water_bala_companyID
            var message = valid(sensorName,location,measuringRange,sensorModel,sensorAccuracy,remarks);
            if(message == null){
            	$.ajax({
                    type: "get",
                    url: "/eva_watersensor_info/insert",
                    data: {
                        'sensorName': sensorName,
                        'location': location,
                        'measuringRange': measuringRange,
                        'sensorModel': sensorModel,
                        'sensorAccuracy': sensorAccuracy,
                        'remarks': remarks,
                        'companyId':label_entity_water_bala_companyID,
                        'sensorRowId':sensorRowId
                    },
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '插入成功',
                                position: 'top',
                                type: 'success',
                                timeout: 2,
                            });
                            $("#new_data").modal('hide');
                            $('#newSelect_id').val("")
                            $('#newLocation').val("")
                            $('#newRange').val("")
                            $('#newType').val("")
                            $('#newAccuracy').val("")
                            $('#newNote').val("")
                            $("#data_table").bootstrapTable('refresh');
                        } else {
                            bootoast({
                                message: '插入失败\n' + data['msg'],
                                position: 'top',
                                type: 'warning',
                                timeout: 2,
                            });
                        }
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            }else{
            	bootoast({
                    message: message,
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
            
        });
        
      //编辑框内的提交
        $('#edit_data_submit').click(function () {
            var id = $("#data_table").bootstrapTable('getSelections')[0]['id'];
            var sensorName = $('#editSelect_id').val()
            var location = $('#editLocation').val()
            var measuringRange = $('#editRange').val()
            var sensorModel = $('#editType').val()
            var sensorAccuracy = $('#editAccuracy').val()
            var remarks = $('#editNote').val()
            var sensorRowId = $('#editSelect2_id').val()
            var message = valid(sensorName,location,measuringRange,sensorModel,sensorAccuracy,remarks,sensorRowId);
            if(message == null){
            	$.ajax({
                    type: "get",
                    url: "/eva_watersensor_info/update",
                    data:{
                    	'id':id,
                        'sensorName': sensorName,
                        'location': location,
                        'measuringRange': measuringRange,
                        'sensorModel': sensorModel,
                        'sensorAccuracy': sensorAccuracy,
                        'remarks': remarks,
                        'companyId':label_entity_water_bala_companyID,
                        'sensorRowId':sensorRowId
                    },
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '修改成功',
                                position: 'top',
                                type: 'success',
                                timeout: 2,
                            });
                            $("#edit_data").modal('hide');
                            $("#data_table").bootstrapTable('refresh');
                        } else {
                            bootoast({
                                message: '修改失败\n' + data['msg'],
                                position: 'top',
                                type: 'warning',
                                timeout: 2,
                            });
                        }
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            }else{
            	bootoast({
                    message: message,
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
            
        });

    };
    return oInit;
};

$(function () {
    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    
    $('#data_table').bootstrapTable('hideColumn', 'id');

});

function change(title,num,text){

	var values=["所在位置","计量范围","水表型号","水表精度","备注"];
	if(text==0){
		var els =document.getElementsByName("new");
	}else{
		var els =document.getElementsByName("edit");
	}
	for(var i=0;i<bigdata.results.length;i++){

    	if(bigdata.results[i].名称==title && bigdata.results[i].设备编号==num){

    		for(var j=0;j<els.length;j++){
    			if(values[j] in bigdata.results[i]){
    				var p = values[j]
    				els[j].value=bigdata.results[i][p];
        		}
    		}

    	}
	}
}

function sortdata(data){
//    var len = data.length
//    var name_arr = new Array()
//    var num_arr = new Array()
//    for(k=0;k<len;k++){
//        num_arr[k]=new Array()
//    }
//    var cnt=0
//    for(var i=0;i<data.length;i++){
//        var name = data[i].名称
//        var num = data[i].设备编号
//        if(name_arr.indexOf(name)==-1){
//            name_arr.push(name)
//            num_arr[cnt].push(num)
//            cnt=cnt+1
//            $("#newSelect_id").append("<option value='"+name+"'>"+name+"</option>");
//        }else{
//            num_arr[cnt].push(num)
//        }
//    }
//     $('#newSelect_id').change(function (){
//        $("#newSelect2_id").empty();
//        var sensorName = $('#newSelect_id').val()
//
//        for(var k=0;k<name_arr.length;k++){
//            if(name_arr[k]==sensorName){
//                for(i=0;i<num_arr[k].length;i++){
//                    $("#newSelect2_id").append("<option value='"+num_arr[k][i]+"'>"+num_arr[k][i]+"</option>");
//                }
//                change(sensorName,num_arr[k][0],0);
//                break
//            }
//        }
//        $('#newSelect2_id').change(function (){
//            var sensorNum = $('#newSelect2_id').val()
//            change(sensorName,sensorNum,0);
//        })
//     })


}
function getOtherSensorInfo(entity_sensor_company_id){
$.ajax({
    type: 'get',
    url: '/chart/selectSensorBySensorId',
    data: {
        'businessId': entity_sensor_company_id,
        'sensorId':$('#newSelect2_id').val()
    },
    dataType: 'json',
    async: false,
    contentType: "application/json; charset=utf-8",
    success: function (res) {
        let data = res.results[0]
        $('#newLocation').empty();
        $('#newLocation').val(data.所在位置);
        $('#newRange').empty();
        $('#newRange').val(data.计量范围);
        $('#newType').empty();
        $('#newType').val(data.水表型号);
        $('#newAccuracy').empty();
        $('#newAccuracy').val(data.水表精度);
    },
});
}
function getOtherSensorInfoEdit(entity_sensor_company_id){
$.ajax({
    type: 'get',
    url: '/chart/selectSensorBySensorId',
    data: {
        'businessId': entity_sensor_company_id,
        'sensorId':$('#editSelect2_id').val()
    },
    dataType: 'json',
    async: false,
    contentType: "application/json; charset=utf-8",
    success: function (res) {
        let data = res.results[0]
        $('#editLocation').empty();
        $('#editLocation').val(data.所在位置);
        $('#editRange').empty();
        $('#editRange').val(data.计量范围);
        $('#editType').empty();
        $('#editType').val(data.水表型号);
        $('#editAccuracy').empty();
        $('#editAccuracy').val(data.水表精度);
    },
});
}

function valid(sensorName,location,measuringRange,sensorModel,sensorAccuracy,remarks){
	if(""==sensorName){
		return "请输入水表名称";
	}
	if(""==location){
		 return "请输入所在位置";
	}
	 if(""==measuringRange){
			return "请输入计量范围";
		}
	 if(""==sensorModel){
			return "请输入水表型号";
		}
	 if(""==sensorAccuracy){
			return "请输入水表精度";
		}
//	 if(""==remarks){
//			return "请输入备注";
//		}
	return null; 
}
//返回上级页面
$("#btn_return").click(function () {
	label_water_bala_companyId=label_entity_water_bala_companyID;
    $('#page-wrapper').load('pages/label_entity_water_bala.html');
});

